<template>
  <div class="chat-container">
    <!-- 只显示第一个会话项，展示对方头像和昵称 -->
    <div class="chat-sidebar">
      <div v-if="chatList.length > 0" class="chat-item active">
        <img :src="chatList[0].avatar || '/default-avatar.png'" class="wx-avatar" />
        <div class="wx-info">
          <span class="wx-title">{{ chatList[0].nickname }}</span>
        </div>
      </div>
    </div>
    <!-- 聊天主区 -->
    <div class="chat-main">
      <div class="chat-header">
        <img v-if="avatar" :src="avatar" class="chat-header-avatar" />
        <span>{{ nickname || activeChatName }}</span>
      </div>
      <div class="chat-messages" ref="msgBox">
        <div v-for="(msg, idx) in messages.filter(m => m.content)" :key="msg.id">
          <div :class="['msg-row', msg.is_self ? 'self' : 'other']">
            <template v-if="msg.is_self">
              <div class="msg-bubble self">{{ msg.content }}</div>
              <img :src="msg.avatar || '/default-avatar.png'" class="msg-avatar self" />
            </template>
            <template v-else>
              <img :src="msg.avatar || '/default-avatar.png'" class="msg-avatar other" />
              <div class="msg-bubble other">{{ msg.content }}</div>
            </template>
          </div>
        </div>
      </div>
      <div class="chat-input">
        <input v-model="inputMsg" @keyup.enter="sendMsg" placeholder="输入消息..." />
        <button @click="sendMsg">发送</button>
      </div>
    </div>
  </div>
</template>
  
  <script setup>
  import { ref, onMounted, nextTick, onBeforeUnmount, h, computed } from 'vue'
  import request from '@/utils/request'
  import { useRouter, useRoute } from 'vue-router'
  import { ElNotification } from 'element-plus'
  import { useUserStore } from '../stores/user'
  import { useChatStore } from '@/stores/chat'
  import {
    connectRoomWs,
    addWsListener,
    removeWsListener,
    sendWsMessage,
    closeWs,
    getCurrentRoomId,
    getWsInstance
  } from '@/utils/globalWs'
  
  let ws = null;
  const chatList = ref([]) // 用户/会话列表
  const activeChatId = ref(null)
  const activeChatName = ref('')
  const messages = computed(() => chatStore.messages)
  const inputMsg = ref('')
  const msgBox = ref(null)
  
  const token = localStorage.getItem('token')
  const user_id = localStorage.getItem('userid')
  
  const router = useRouter()
  const route = useRoute()
  const nickname = route.query.nickname
  const avatar = route.query.avatar
  const targetUserId = route.params.userId || route.query.userId // 目标用户id
  
  const myNickname = localStorage.getItem('nickname') || user_id // 你的手机号或昵称
  const userStore = useUserStore()
  const myAvatar = computed(() => userStore.avatar || localStorage.getItem('avatar') || '/default-avatar.png')
  
  const chatStore = useChatStore()

  function scrollToBottom() {
    nextTick(() => {
      if (msgBox.value) msgBox.value.scrollTop = msgBox.value.scrollHeight
    })
  }

  function handleWsMessage(type, data) {
    console.log('[WS收到消息]', type, data)
    if (type === 'chat_message') {
      const msg = data.message
      const myId = String(localStorage.getItem('userid'))
      const normalizedMsg = {
        id: msg.id,
        content: msg.content,
        user_id: msg.sender?.id,
        nickname: msg.sender?.nickname,
        avatar: msg.sender?.avatar,
        room_id: msg.room_id,
        is_self: String(msg.sender?.id) === myId
      }
      if (normalizedMsg.is_self) {
        const idx = chatStore.messages.findIndex(m =>
          m.is_self && m.content === normalizedMsg.content && String(m.id).startsWith('local_')
        )
        if (idx !== -1) {
          chatStore.messages[idx].id = normalizedMsg.id
        } else if (!chatStore.messages.find(m => m.id === normalizedMsg.id)) {
          chatStore.addMessage(normalizedMsg)
        }
      } else {
        if (!chatStore.messages.find(m => m.id === normalizedMsg.id)) {
          chatStore.addMessage(normalizedMsg)
        }
      }
      scrollToBottom()
      notifyNewMessage(normalizedMsg)
    } else if (type === 'history_messages') {
      console.log('[WS历史消息]', data)
      chatStore.clearMessages()
      const myId = String(localStorage.getItem('userid'))
      data.messages.forEach(msg => {
        chatStore.addMessage({
          id: msg.id,
          content: msg.content,
          user_id: msg.sender?.id,
          nickname: msg.sender?.nickname,
          avatar: msg.sender?.avatar,
          room_id: msg.room_id,
          is_self: String(msg.sender?.id) === myId
        })
      })
      scrollToBottom()
    } else if (type === 'messages_read') {
      console.log('[WS已读回执]', data)
      // 可扩展：已读回执
    } else if (type === 'user_typing') {
      console.log('[WS正在输入]', data)
      // 可扩展：正在输入
    } else if (type === 'connection_established') {
      console.log('[WS连接成功]', data)
      // 连接成功
    } else if (type === 'global_message') {
      console.log('[WS全局通知]', data)
      // 全局通知
      ElNotification({
        title: '全局通知',
        message: h('i', { style: 'color: teal' }, data.message.content),
        duration: 3000
      })
    } else if (type === 'pong') {
      // 心跳
    } else if (type === 'error') {
      // data 已经是对象，直接用，不要再 JSON.parse data.raw
      console.error('[WS错误]', data)
      ElNotification({ title: '错误', message: data.message, type: 'error' })
    }
  }

  // 顶部定义具名回调，保证引用唯一
  function handleChatMessage(d) { handleWsMessage('chat_message', d) }
  function handleHistoryMessages(d) { handleWsMessage('history_messages', d) }
  function handleMessagesRead(d) { handleWsMessage('messages_read', d) }
  function handleUserTyping(d) { handleWsMessage('user_typing', d) }
  function handleConnectionEstablished(d) { handleWsMessage('connection_established', d) }
  function handlePong(d) { handleWsMessage('pong', d) }
  function handleError(d) { handleWsMessage('error', d) }
  function handleGlobalMessage(d) { handleWsMessage('global_message', d) }

  function setupRoomWsListeners() {
    addWsListener('chat_message', handleChatMessage)
    addWsListener('history_messages', handleHistoryMessages)
    addWsListener('messages_read', handleMessagesRead)
    addWsListener('user_typing', handleUserTyping)
    addWsListener('connection_established', handleConnectionEstablished)
    addWsListener('pong', handlePong)
    addWsListener('error', handleError)
  }
  function removeRoomWsListeners() {
    removeWsListener('chat_message', handleChatMessage)
    removeWsListener('history_messages', handleHistoryMessages)
    removeWsListener('messages_read', handleMessagesRead)
    removeWsListener('user_typing', handleUserTyping)
    removeWsListener('connection_established', handleConnectionEstablished)
    removeWsListener('pong', handlePong)
    removeWsListener('error', handleError)
  }
  function setupGlobalWsListeners() {
    addWsListener('global_message', handleGlobalMessage)
  }
  function removeGlobalWsListeners() {
    removeWsListener('global_message', handleGlobalMessage)
  }

  // 工具函数：格式化侧边栏时间（目前未被使用）
  function formatSidebarTime(time) {
    if (!time) return ''
    const d = new Date(time)
    return `${d.getHours()}:${d.getMinutes().toString().padStart(2, '0')}`
  }

  function setActiveRoom(id) {
    activeChatId.value = id
    closeWs()
    connectRoomWs(id)
    const item = chatList.value.find(item => String(item.id) === String(id))
    activeChatName.value = item ? (item.group_name || item.nickname) : ''
  }

  async function selectChat(id) {
    setActiveRoom(id)
  }

  async function fetchChatList() {
    const res = await request.get('/chat/rooms/', {
      headers: { Authorization: `Bearer ${token}` }
    })
    const rooms = res.rooms
    chatList.value = rooms
    if (!rooms || rooms.length === 0) {
      ElNotification({ title: '提示', message: '暂无会话房间', type: 'info' })
      return
    }
    const room_id = rooms[0].id

    // 2. 建立WebSocket连接
    if (ws) ws.close()
    ws = new window.WebSocket(`ws://127.0.0.1:8000/ws/chat/${room_id}/?token=${token}`)
    ws.onopen = () => {
      fetchHistory(room_id)
    }
    ws.onmessage = (event) => {
      const data = JSON.parse(event.data)
      if (data.type === 'chat_message') {
        const isSelf = data.user_id == user_id
        if (isSelf) {
          // 查找本地临时消息
          const idx = chatStore.messages.findIndex(
            m => m.is_self && m.content === data.content && String(m.id).startsWith('local_')
          )
          if (idx !== -1) {
            // 用真实 id 替换
            chatStore.messages[idx].id = data.id
            return
          }
        }
        // 非自己发的消息 或 本地无临时消息，正常 push
        chatStore.addMessage({
          ...data,
          is_self: isSelf
        })
        // 更新联系人最后一句话和时间
        let contact = chatList.value.find(item => item.user_id == (data.user_id == user_id ? data.target_id : data.user_id))
        if (contact) {
          contact.last_message = data.content
          contact.last_time = data.time || new Date().toLocaleTimeString().slice(0,5)
        }
      }
    }
    if (chatList.value.length) {
      setActiveRoom(chatList.value[0].id)
    }
  }

  // onMounted 注册监听
  onMounted(() => {
    fetchChatList()
    setupRoomWsListeners()
    setupGlobalWsListeners()
  })
  onBeforeUnmount(() => {
    removeRoomWsListeners()
    removeGlobalWsListeners()
    closeWs()
  })


  function fetchHistory(room_id) {
    request.get('/chat/messages/', { params: { room_id } }).then(res => {
      chatStore.clearMessages()
      const myId = String(localStorage.getItem('userid'))
      res.messages.forEach(msg => {
        chatStore.addMessage({
          id: msg.id,
          content: msg.content,
          user_id: msg.sender?.id,
          nickname: msg.sender?.nickname,
          avatar: msg.sender?.avatar,
          room_id: msg.room_id,
          is_self: String(msg.sender?.id) === myId
        })
      })
      nextTick(() => {
        msgBox.value.scrollTop = msgBox.value.scrollHeight
      })
    })
  }
  
  function sendMsg() {
    if (!inputMsg.value.trim()) return
    const ws = getWsInstance()
    const wsRoomId = getCurrentRoomId()
    console.log('[WS发送消息前] ws:', ws, 'readyState:', ws ? ws.readyState : 'undefined', 'wsRoomId:', wsRoomId, 'activeChatId:', activeChatId.value)
    // 修正 WebSocket 连接状态判断
    if (!ws || ws.readyState !== 1) {
      ElNotification({ title: '提示', message: 'WebSocket 未连接', type: 'error' })
      return
    }
    if (String(wsRoomId) !== String(activeChatId.value)) {
      ElNotification({ title: '提示', message: `房间号不一致，wsRoomId=${wsRoomId} activeChatId=${activeChatId.value}`, type: 'error' })
      return
    }
    const msgData = {
      content: inputMsg.value,
      message_type: 'text',
      room_id: wsRoomId,
      type: 'chat_message'
    }
    console.log('[WS发送消息]', msgData)
    // 立即本地渲染消息（自己发的）
    const myId = String(localStorage.getItem('userid'))
    const localId = `local_${Date.now()}`
    chatStore.addMessage({
      id: localId,
      content: msgData.content,
      user_id: myId,
      nickname: myNickname,
      avatar: myAvatar.value,
      room_id: wsRoomId,
      is_self: true
    })
    sendWsMessage(msgData)
    inputMsg.value = ''
    scrollToBottom()
  }
  
  // 供外部调用（如私信按钮）
  function startPrivateChat(userId, nickname, avatar) {
    // 跳转到 Chat 页面，并传递 userId
    router.push({ name: 'Chat', params: { userId } })
  }

  function isChatPage() {
    // 判断当前路由是否为聊天页
    return router.currentRoute.value.name === 'Chat';
  }

  function notifyNewMessage(msg) {
    // 只在收到新消息且页面不在Chat时弹一次
    if (!msg.is_self && !isChatPage()) {
      ElNotification({
        title: msg.nickname || '新消息',
        message: h('i', { style: 'color: teal' }, msg.content),
        duration: 3000,
        onClick: () => {
          router.push({ name: 'Chat', params: { userId: msg.user_id } })
        }
      })
    }
  }

  // 工具函数：格式化微信风格日期（目前未被使用）
  function formatWxDate(time) {
    if (!time) return ''
    const d = new Date(time)
    return `${(d.getMonth()+1).toString().padStart(2,'0')}/${d.getDate().toString().padStart(2,'0')}`
  }

  </script>
  
  <style scoped>
  .chat-container {
    display: flex;
    height: 80vh;
    border-radius: 12px;
    box-shadow: 0 2px 12px #0001;
    background: #fff;
    overflow: hidden;
  }
  .chat-sidebar {
    width: 260px;
    background: #f7f8fa;
    border-right: 1px solid #eee;
    overflow-y: auto;
    padding-top: 0;
  }
  .chat-item {
    display: flex;
    align-items: center;
    padding: 8px 12px 8px 16px;
    cursor: pointer;
    border-bottom: 1px solid #f0f0f0;
    transition: background 0.2s;
    height: 60px;
    position: relative;
    background: #f7f8fa;
  }
  .chat-item.active, .chat-item:hover {
    background: #e6f7ff;
  }
  .wx-avatar {
    width: 42px;
    height: 42px;
    border-radius: 8px;
    object-fit: cover;
    margin-right: 10px;
  }
  .wx-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    min-width: 0;
  }
  .wx-title-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 2px;
  }
  .wx-title {
    font-weight: bold;
    color: #222;
    font-size: 15px;
    max-width: 120px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .wx-time {
    color: #b2b2b2;
    font-size: 12px;
    margin-left: 8px;
    flex-shrink: 0;
  }
  .wx-lastmsg {
    color: #888;
    font-size: 13px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-top: 0;
    line-height: 1.3;
  }
  /* 删除 .chat-sidebar、.chat-item、.wx-avatar、.wx-info、.wx-title-row、.wx-title、.wx-time、.wx-lastmsg 相关样式 */
  .chat-main {
    flex: 1;
    display: flex;
    flex-direction: column;
  }
  .chat-header {
    padding: 16px;
    border-bottom: 1px solid #eee;
    font-size: 18px;
    font-weight: bold;
    color: #19c37d;
  }
  .chat-header-avatar {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    margin-right: 10px;
    vertical-align: middle;
  }
  .chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 18px;
    background: #f9f9fb;
  }
  .chat-message {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    margin-bottom: 12px;
  }
  .chat-message.self {
    align-items: flex-end;
  }
  .msg-meta {
    display: flex;
    align-items: center;
    margin-bottom: 2px;
  }
  .msg-meta.self {
    flex-direction: row-reverse;
  }
  .msg-row {
    display: flex;
    align-items: center; /* 垂直居中对齐头像和气泡 */
    margin-bottom: 16px;
    /* 保持与父容器padding一致，防止气泡贴边 */
    padding: 0;
  }
  .msg-row.self {
    justify-content: flex-end;
  }
  .msg-row.other {
    justify-content: flex-start;
  }
  .msg-avatar {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    object-fit: cover;
  }
  .msg-avatar.self {
    margin-left: 12px;
    margin-right: 0;
  }
  .msg-avatar.other {
    margin-right: 12px;
    margin-left: 0;
  }
  .msg-bubble {
    max-width: 260px;
    min-width: 36px;
    padding: 6px 10px;
    font-size: 14px;
    line-height: 1.5;
    word-break: break-all;
    min-height: 32px;
    display: flex;
    align-items: center;
    box-shadow: 0 1px 1.5px #0001;
  }
  .msg-bubble.self {
    background: #95ec69;
    color: #222;
    border-radius: 8px 8px 2px 8px;
  }
  .msg-bubble.other {
    background: #fff;
    color: #222;
    border-radius: 8px 8px 8px 2px;
  }
  .chat-input {
    display: flex;
    padding: 12px 16px;
    border-top: 1px solid #eee;
    background: #fafbfc;
  }
  .chat-input input {
    flex: 1;
    border-radius: 6px;
    border: 1px solid #eee;
    padding: 8px 12px;
    font-size: 15px;
  }
  .chat-input button {
    background: #19c37d;
    color: #fff;
    border: none;
    border-radius: 6px;
    padding: 8px 18px;
    margin-left: 10px;
    font-size: 15px;
    cursor: pointer;
  }
  </style>